package y2018.date0912.批量下载;

import com.lu.jdog.util.FileUtil;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.text.NumberFormat;

public class DownUtil {
    /**
     * 下载
     *
     * @param urls 连接
     * @param dir  目录
     * @param def  默认后缀
     */
    public static void downLoad(String[] urls, String dir, String def) {
        new File(dir).mkdirs();
        NumberFormat nf = NumberFormat.getPercentInstance();
        nf.setMinimumFractionDigits(2);

        for (int i = 0; i < urls.length; i++) {
            String urlStr = urls[i];
            try {
                int dotIndex = urlStr.lastIndexOf(".");
                String fileName = (i + (dotIndex > 0 ? urlStr.substring(dotIndex, urlStr.length()) : def));
                File file = new File(dir + "/" + fileName);

                URL url = new URL(urlStr);
                URLConnection conn = url.openConnection();
                BufferedInputStream bis = new BufferedInputStream(conn.getInputStream());
                OutputStream os = new FileOutputStream(file);
                FileUtil.write(bis, os);

                System.out.println(nf.format((i + 1.0f) / urls.length));

            } catch (MalformedURLException e) {

                e.printStackTrace();
            } catch (IOException e) {

                e.printStackTrace();
            }

        }
    }

}
